package it.sarasini.dmp;

import java.io.File;

import org.farng.mp3.MP3File;

import android.content.Context;

public class SongInfo {

	private static final String NO_TITLE = "No title";
	private static final String NO_ARTIST = "No Artist";
	private static final String NO_ALBUM = "No Album";
	private File audioFile;
	
	private String artist = NO_ARTIST;
	private String title = NO_TITLE;
	private String album = NO_ALBUM;
	private int length = 0;
	
	
	public SongInfo(Context c, File audioFile) {
		
		this.audioFile = audioFile;
		
		artist = retriveArtist(this.audioFile);
		title = retriveTitle(this.audioFile);
		album = retriveAlbum(this.audioFile);
		
		AudioVideoPlayer avp = new AudioVideoPlayer(c);
		
		avp.loadAudioFile(this.audioFile);
		length = avp.getDuration();
		
		avp = null;
	}
	
	public String retriveArtist(File f) {
		
		MP3File mp3file;
		String artist = NO_ARTIST;
		
		try {
			
			mp3file = new MP3File(f);
			
			artist = mp3file.getID3v2Tag().getLeadArtist();
			
		} catch (Exception e) { DebugLog.log("error MP3File: " + e.getMessage()); return NO_ARTIST; }
		
		artist = removeIllegalCharacters(artist);
		
		return artist;
	}
	
	public String retriveTitle(File f) {
			
		MP3File mp3file;
		String title = NO_TITLE;
		
		try {
			
			mp3file = new MP3File(f);
			
			title = mp3file.getID3v2Tag().getSongTitle();
			
		} catch (Exception e) { DebugLog.log("error MP3File: " + e.getMessage()); return NO_TITLE; }
		
		title = removeIllegalCharacters(title);
		
		return title;
	}
	
	public String retriveAlbum(File f) {
		
		MP3File mp3file;
		String album = NO_ALBUM;
		
		try {
			
			mp3file = new MP3File(f);
			
			album = mp3file.getID3v2Tag().getAlbumTitle();
			
		} catch (Exception e) { DebugLog.log("error MP3File: " + e.getMessage()); return NO_ALBUM; }
		
		album = removeIllegalCharacters(album);
		
		return album;
	}
	
	public String removeIllegalCharacters(String str) {
		
		String strNew = "";
		
		for(int i=0; i<str.length(); i++) {
			
			if((str.charAt(i) >= 32)&&(str.charAt(i) <= 125))
				strNew = strNew + str.charAt(i);
		}
		
		return strNew;
	}

	public String getArtist() {
		
		return artist;
	}

	public String getTitle() {
		
		return title;
	}

	public String getAlbum() {
		
		return album;
	}

	public int getLength() {
		
		return length;
	}
	
	
}
